<template>
  <div>
    <!-- 添加新的申购表 -->
    <Modal v-model="onAddApplyTable" :styles="{width: '90vw'}"
    :mask-closable="false" >
      <p slot="header" style="color:#19be6b;text-align:center">
        <Icon type="information-circled"></Icon>
        <span>添加申购表</span>
      </p>
      <add-apply-table :projectId="projectId" @add-apply-table="updateApplyTable" :method="'newTable'" :itemTypeList="itemTypeList"></add-apply-table>
      <div slot="footer">
        <Button type="success" size="large" style="width:100px;"  
        @click="handleAddApplyTableOk" :loading="add_modal_loading">确定</Button>
      </div>
    </Modal>
    <!-- 添加物品到申购表-->
    <Modal v-model="onAddToItemList" :styles="{width: '90vw'}" :mask-closable="false">
      <p slot="header" style="color:#19be6b;text-align:center">
        <Icon type="information-circled"></Icon>
        <span>添加物品</span>
      </p>
      <add-apply-table  @add-apply-table="handleAddToItemList" :method="'updateTable'" :itemTypeList="itemTypeList"></add-apply-table>
      <div slot="footer">
        <Button type="success" size="large" style="width:100px;" @click="handleAddToItemListOk" :loading="add_to_itemlist_modal_loading">确定</Button>
      </div>
    </Modal>
    <Card style="padding: 0 40px;">
      <h1 slot="title">
        <Icon type="ios-film-outline"></Icon>
        {{projectName}}
        <Button type="success" @click="handleAddApplyTableButtonClick">
          <Icon type="android-add"></Icon>
          增加申购表
        </Button>
        <Button type="success" @click="handleAddItemTypeButtonClick">
          <Icon type="android-add"></Icon>
          增加物品类型
        </Button>
      </h1>

      <ul style="display:flex;justify-content:space-between; margin-bottom: 20px;">
        <li v-for="(item, index) in projectInfoList" style="display: inline-block;max-width:20%;" v-if="item.key !== '项目id'" :key="index">
          <div >
            <Tag color="blue">{{item.key}}</Tag>
            <p style="font-size: 20px;font-weight: bold;line-height: 30px;">{{item.value}}</p>
          </div>
        </li>
      </ul>
      <Spin size="large" v-if="isLoading" fix></Spin>
      <Timeline v-if="!isLoading">
        <TimelineItem v-for="(table,index) in projectApplyTableList" :key="index">
          <timestamp :timestamp="table.time"></timestamp>
          <Spin size="large" v-if="!table.details" fix></Spin>
          <div style="margin-bottom: 20px;">
            <Button type="error" @click="handleDeleteApplyTableButtonClick(table.table_id)" :disabled="table.commons[0].status === '5'">
              <Icon type="android-delete" ></Icon>
              删除申购表
            </Button>
            <Button type="warning" @click="handleResendApplyTableOk(table)" v-if="table.status === '2' || table.status === '4'">
              <Icon type="ios-paperplane"></Icon>
              再次申请
            </Button>
          </div>
          <Table :data="table.details" :columns="columns1" border v-if="table.details"></Table>
          <Table :data="table.commons" :columns="columns2" border v-if="table.details"></Table>
          <br>
          <div v-if="table.comment">
            <Tag color="orange" type="dot" style="margin-bottom: 20px;" v-if="table.comment !== ''">建议</Tag>

            <blockquote style="font-size: 25px; border-left:5px solid #f00; padding-left:10px; background: #fcfcfc;">
              {{table.comment}}
            </blockquote>
          </div>
          
        </TimelineItem>

      </Timeline>
    </Card>

  </div>

</template>

<script>
import querystring from 'querystring';
import { HOST } from '../../libs/config.js';
import {loginInvalid} from "../../libs/loginInvalidNotice.js";
import timestamp from './timestamp.vue';
import addApplyTable from './addApplyTable';
import inforCard from '../home/components/inforCard';
import util from "../../libs/util.js";
export default {
  components: {
    timestamp,
    addApplyTable,
    inforCard
  },
  data() {
    return {
      newType: '',
      itemTypeList: [],
      currentTableId: -1,
      onAddToItemList: false,
      itemList: [],
      add_modal_loading: false,
      onAddApplyTable: false,
      projectInfoList: [],
      newApplyTable: {},
      add_to_itemlist_modal_loading: false,
      ApplyTableStatus: [
        '未被审核',
        '部门主管审核通过',
        '部门主管驳回',
        '中心主管审核通过',
        '中心主管驳回',
        '已入库'
      ],
      projectNameList: {
        'project_id': '项目id',
        'name': '项目名称',
        'money': '项目金额',
        'balance': '可用余额',
        'summary': '项目描述',
        'leader': '项目负责人',
        'leader_phone': '负责人联系方式',
        'teacher': '指导老师',
        'teacher_phone': '指导老师联系方式',
      },
      projectApplyTableList:[],
      isLoading: false,
      columns1:
      [
        {
          title: '序号',
          key: 'name',
          render: (h, params) => {
            // console.log(params);
            return h('div', {
            }, params.index + 1)
          }
        },
        {
          title: '名称',
          key: 'name'
        }, 
        {
          title: '物品类型',
          key: 'store_type',
          render: (h, params) => {
            let result = !params.row.store_type ? '' : h('Tag', {
              props: {
                color: 'blue'
              }
            }, params.row.store_type);
            return result;
          }
        },
        {
          title: '型号及主要技术指标数量',
          key: 'type',
          width: 220
        },
        {
          title: '数量',
          key: 'num'
        },
        {
          title: '采购预算(万元)',
          key: 'money'
        },
        {
          title: '推荐厂家',
          key: 'vender'
        },
        {
          title: '拟购时间',
          key: 'time',
          render: (h, params) => {
            return h('span', params.row.time);
            // new Date(parseInt(params.row.time) * 1000).toLocaleDateString().replace(/\//g, '-')
          }
        },
        {
          title: '用途',
          key: 'for'
        },
        {
          title: '设备安放地点',
          key: 'place'
        },
        {
          title: '',
          fix: 'right',
          align: 'center',
          render: (h, params) => {
            return params.row.status === '5' ? null
              :  h('i-button', {
              props: {
                type: 'error',
              },
              on: {
                click: () => {
                  this.$Modal.confirm({
                    title: '删除物品',
                    content: `你确定要删除该物品么?`,
                    onOk: () => {
                      this.$axios.post(HOST + '/project/goodsDel', querystring.stringify({
                          'item_id': params.row.item_id
                        }), {
                          withCredentials: true
                        })
                        .then((response) => {
                          this.$Modal.remove();
                          if (response.data.status === 'success') {
                            let i = null;
                            this.projectApplyTableList.forEach((item, index) => {
                              if (item.table_id === params.row.table_id) {
                                i = index;
                              }
                            });
                            this.refreshTable(i);
                            this.$Notice.success({
                              title: '删除成功',
                              desc: `物品${params.row.name}删除成功`,
                              duration: 2
                            });
                          } else {
                            this.$Notice.error({
                              title: '删除失败',
                              desc: `物品${params.row.name}删除失败`,
                              duration: 2
                            });
                          }
                        })
                        .catch((err) => {
                          if (err.data.status === 'invalid Token') {
                            loginInvalid(this)();
                          }
                        })
                    },
                    onCancel: () => {
                      this.$Modal.remove();
                    }
                  });
                }
              }
            }, '删除')

          },
          renderHeader: (h, params) => {
            return h('i-button', {
            props: {
              type: 'success',
            },
            class: {
              'add-item-add': true,
            },
            on: {
              click: (e) => {
                let i = null;
                document.querySelectorAll('.add-item-add').forEach((item, index) => {
                  if (e.target.parentElement.parentElement === item) {
                    i = index;
                  }
                })
                this.currentTableId = this.projectApplyTableList[i].table_id;
                this.onAddToItemList = true;
              }
            }
          }, [
            h('Icon', {
              props: {
                type: 'android-add'
              }
            }),
            h('span', '增加物品')
          ])
        }
        }
      ],
    columns2: 
      [
        {
          title: '合计金额(万元)',
          key: 'sum_money'
        }, 
        {
          title: '经办人及联系电话',
          key: 'man_phone',
          width: 250
        },
        {
          title: '经费来源情况(项目名称及经费号)',
          key: 'expense'
        },
        {
          title: '部门审核负责人',
          key: 'dep_audit'
        },
        {
          title: '中心审核主管领导',
          key: 'center_audit'
        },
        {
          title: '状态',
          key: 'status',
          align: 'center',
          render: (h, params) => {
            return h('Tag', {
              props:{
                color: this.getStatusColor(params.row.status)
              }
            }, this.ApplyTableStatus[parseInt(params.row.status)])
          }
        },

      ],
    }
  },
  methods: {
    getProjectInfo() {
      this.isLoading = true;
      this.$axios.get(HOST + '/project/list', {
          withCredentials: true
        })
        .then((response) => {
          let data = response.data;
          if (data.length > 0) {
            let curProject = data.filter((item) => {
              return item.project_id === this.projectId;
            })[0];
            let nameList = Object.keys(curProject);
            nameList.forEach((item) => {
              if (this.projectNameList[item]) {
                this.projectInfoList.push({
                  key: this.projectNameList[item],
                  value: curProject[item]
                });
              }
            })
            // this.loadTable = false;
          }
        })
        .catch((err) => {
          if (err.data.status && err.data.status === 'invalid Token') {
            loginInvalid(this)();
          } else {

          }
        })
    },
    getProjectApplyList() {
      this.refreshProjectApplyList();
    },
    getStatusColor(status) {
      if (status === '0') {
        return 'gray'
      } else if (status === '2' || status === '4') {
        return 'red';
      } else if (status === '5'){
        return 'green';
      } else {
        return 'orange';
      }
    },
    handleDeleteApplyTableButtonClick(tableId) {
      this.$Modal.confirm({
        loading: true,
        title: '删除申购表',
        onOk: () => {
          this.handleDeleteApplyTableOk(tableId);
        },
        onCancel: () => {
          this.$Modal.remove();
        }
      })
    },
    handleResendApplyTableOk(table) {
      let res = {};
      res.details = table.details;
      res.common = table.commons[0];
      res.table_id = table.table_id;
      // console.log(res);
      this.$axios.post(HOST + '/project/updateApply',
          {
            applyTable: res
          }, {
            withCredentials: true
          })
        .then((response) => {
          this.$Modal.remove();
          if (response.data.status === 'success') {
            this.refreshProjectApplyList();
            this.$Notice.success({
              title: '申请成功',
              desc: `申购表申请成功`,
              duration: 2
            });
          } else {
            this.$Notice.error({
              title: '申请失败',
              desc: `申购表申请失败`,
              duration: 2
            });
          }
        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        })
    },
    handleDeleteApplyTableOk(tableId) {
      
      this.$axios.post(HOST + '/project/tableDel',
          querystring.stringify({
            'id': tableId,
          }), {
            withCredentials: true
          })
        .then((response) => {
          this.$Modal.remove();
          if (response.data.status === 'success') {
            this.refreshProjectApplyList();
            this.$Notice.success({
              title: '删除成功',
              desc: `申购表删除成功`,
              duration: 2
            });
          } else {
            this.$Notice.error({
              title: '删除失败',
              desc: `申购表删除失败`,
              duration: 2
            });
          }
        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        })
    },
    handleAddApplyTableButtonClick() {
      this.onAddApplyTable = true;
    },
    handleAddItemTypeButtonClick() {
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              value: this.newType,
              autofocus: true,
              placeholder: '请输入新物品分类'
            },
            on: {
              input: (val) => {
                this.newType = val;
              }
            }
          })
        },
        loading: true,
        title: '增加物品分类',
        onOk: () => {
          this.handleAddType();
        },
        onCancel: () => {
          this.$Modal.remove();
        }
      })
    },
    handleAddType() {
      this.$axios.post(HOST + '/store/typeAdd',
          querystring.stringify({
            name: this.newType
          }), {
            withCredentials: true
          }
        )
        .then((response) => {
          this.newType = '';
          this.$Modal.remove();
          if (response.data.status === 'success') {
            this.$Notice.success({
              title: '添加成功',
              desc: `物品类型添加成功`
            });
          } else {
            this.$Notice.error({
              title: '添加失败',
              desc: `物品类型添加失败`
            });
          }
        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        })
    },
    updateApplyTable(table1, table2) {
      this.newApplyTable.details = table1;
      this.newApplyTable.common = table2[0];
    },
    handleAddApplyTableOk() {
      if (!this.newApplyTable) {
        return;
      }
      let re = false;
      re = this.newApplyTable.details.some((item) => {
        return util.isEmpty(item);
      })
      if (re || util.isEmpty(this.newApplyTable.common)) {
        this.$Notice.error({
          title: '添加失败',
          desc: `有未填写的项目`,
          duration: 2
        });
        return;
      }

      this.newApplyTable.common.project_id = this.projectId;
      this.add_modal_loading = true;
      this.$axios.post(HOST + '/project/newApply',
          {
            'applyTable': this.newApplyTable,
          }, {
            withCredentials: true
          })
        .then((response) => {
          this.onAddApplyTable = false;
          this.add_modal_loading = false;
          if (response.data.status === 'success') {
            this.newApplyTable = {};
            this.$Notice.success({
              title: '添加成功',
              desc: `申购表添加成功`,
              duration: 2
            });
            this.refreshProjectApplyList();
          } else {
            this.$Notice.error({
              title: '添加失败',
              desc: `申购表添加失败`,
              duration: 2
            });
          }

        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        })
    },
    refreshProjectApplyList() {
      this.$axios.get(HOST + `/project/pTablesList?id=${this.projectId}`, {
          withCredentials: true
        })
        .then((response) => {
          this.isLoading = false;
          let data = response.data;
          this.projectApplyTableList = data;
          this.projectApplyTableList.forEach((item) => {
            let commonObj = {};
            item.commons = [];
            let keyList = Object.keys(item);
            keyList.forEach((key) => {
              if (key !== 'details' && key !== 'commons') {
                commonObj[key] = item[key];
              }
            })
            item.commons.push(commonObj);
            // item.commons = Object.keys(item);
            this.$axios.get(HOST + `/project/goodsList?table_id=${item.table_id}`, {
                withCredentials: true
              })
              .then((res) => {
                item.details = res.data;
                item.details.forEach((_item) => {
                  _item.table_id = item.table_id;
                  _item.status = item.status;
                })
                this.$forceUpdate();
              });

          })
        })
        .catch((err) => {
          if (err.data.status && err.data.status === 'invalid Token') {
            loginInvalid(this)();
          } else {

          }
        })
    },
    handleAddToItemList(table1) {
      this.itemList = table1;
    },
    handleAddToItemListOk() {
      if (this.itemList.length < 1) {
        return ;
      }
      let re = false;
      re = this.itemList.some((item) => {
        return util.isEmpty(item);
      })
      if (re) {
        this.$Notice.error({
          title: '添加失败',
          desc: `有未填写的项目`,
          duration: 2
        });
        return;
      }

      this.add_to_itemlist_modal_loading = true;
      this.$axios.post(HOST + '/project/goodAdd', {
          'applyItemList': {
            'table_id': this.currentTableId,
            'details': this.itemList
          }
        }, {
          withCredentials: true
        })
        .then((response) => {
          this.onAddToItemList = false;
          this.add_to_itemlist_modal_loading = false;
          
          if (response.data.status === 'success') {
            let _i = null;
            this.projectApplyTableList.forEach((item, index) => {
              if (item.table_id === this.currentTableId) {
                _i = index;
              }
            })
            this.refreshTable(_i);
            this.$Notice.success({
              title: '添加成功',
              desc: `物品添加成功`,
              duration: 2
            });
            // this.refreshTable(this.currentTableId);
          } else {
            this.$Notice.error({
              title: '添加失败',
              desc: `物品添加失败`,
              duration: 2
            });
          }

        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        })
    },
    refreshTable(tableIndex) {
      let tableId = this.projectApplyTableList[tableIndex].table_id;
      this.projectApplyTableList[tableIndex].details = null;
      this.$axios.get(HOST + `/project/goodsList?table_id=${tableId}`, {
          withCredentials: true
        })
        .then((res) => {
          let details = [];
          details = res.data;
          details.forEach((_item) => {
            _item.table_id = tableId;
          })
          this.projectApplyTableList[tableIndex].details = details;
          this.$forceUpdate();
        });
    },
    refreshItemTypeList(tableIndex) {
      this.$axios.get(HOST + '/store/storeType', {
          withCredentials: true
        })
        .then((res) => {
          this.itemTypeList = res.data;
        });
    }
  },
  computed: {
    projectId() {
      return this.$router.currentRoute.params.projectId;
    },
    projectName() {
      return this.$router.currentRoute.params.projectName;
    }
  },
  mounted() {
    this.getProjectInfo();
    this.refreshProjectApplyList();
    this.refreshItemTypeList();
  }
}
</script>
<style>
  .add-apply-table-cover {
    position: absolute;
    z-index: 999;
    width:100%;
    height: 100%;
    background: #ccc;

  }
</style>